package org.jl.main;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.annotation.JSONField;
import lombok.Data;
import org.jl.main.model.User;

import java.util.List;
import java.util.Map;

/*
Fastjson
小技巧：如果控制台打印了json，可以选中json右键选择显示为JSON，即可在新窗口看到格式化的json
 */
public class Main04_2_Fastjson {

    /*
    构建对象
     */
    public static void main0(String[] args) {
        JSONObject json1 = new JSONObject();
        json1.put("userCode", "0001");
        json1.put("userName", "张三");
        String jsonStr1 = JSON.toJSONString(json1);
        System.out.println("json1 string = " + jsonStr1 + "\n");
        //格式化打印
        String jsonStr2 = JSON.toJSONString(json1, JSONWriter.Feature.PrettyFormat);
        System.out.println("json2 string = " + jsonStr2);

        JSONArray array1 = new JSONArray();
        JSONObject json2 = new JSONObject();
        json2.put("userCode", "0002");
        json2.put("userName", "李四");
        array1.add(json1);
        array1.add(json2);
        String jsonStr3 = JSON.toJSONString(array1);
        System.out.println("array1 = " + jsonStr3 + "\n");
    }

    /*
    对象
     */
    public static void main1(String[] args) {
        User u1 = User.builder().userCode("0001").userName("张三").userAge(18).build();
        String u2Str = "{\"userCode\":\"0002\",\"userName\":\"李四\",\"userAge\":18}";

        //对象转字符串
        String u1Str = JSON.toJSONString(u1);
        System.out.println("u1 string = " + u1Str + "\n");

        //字符串转JSON对象
        @SuppressWarnings("unchecked")
        Map<String, Object> u2Obj = JSONObject.parseObject(u2Str, Map.class);
        System.out.println("u2 json = " + u2Obj + "\n");

        //字符串转对象
        User u2 = JSONObject.parseObject(u2Str, User.class);
        System.out.println("u2 = " + u2 + "\n");

        String codeStr = "{\"e_code\":\"0001\",\"c_code\":\"1001\"}";
        Code code = JSONObject.parseObject(codeStr, Code.class);
        System.out.println("code = " + code + "\n");
    }

    /*
    数组
     */
    public static void main2(String[] args) {
        //列表转字符串
        String array1Str = JSON.toJSONString(Main02_2_Collection.USERS1);
        System.out.println("array1 string = " + array1Str + "\n");

        //字符串转列表
        List<User> users1 = JSON.parseArray(array1Str, User.class);
        System.out.println("users1 = " + users1 + "\n");

        JSONArray array1 = JSON.parseArray(JSON.toJSONString(Main02_2_Collection.USERS1));
        System.out.println("array1 = " + array1 + "\n");
    }
}

@Data
class Code {
    private String e_code;
    private String eCode;
    @JSONField(name = "c_code")
    private String cCode;
}